package com.mrper.test

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.webkit.ValueCallback
import androidx.core.content.FileProvider
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.mrper.filedialog.data.adapter.FileManagerAdapter
import com.mrper.filedialog.ui.FileManagerActivity
import com.mrper.filedialog.utils.io.getUriFromFileProvider
import java.io.File
import java.util.*

class WebViewFileUploader(
    private val activity: Activity,
    filePathCallback: ValueCallback<Array<Uri>>?,
    acceptType: String?
) {

    private var fileUploadCallback: ValueCallback<Array<Uri>>? = filePathCallback

    init {
        when {
            acceptType?.toLowerCase(Locale.getDefault())?.startsWith("image/*") == true -> pickPicture()
            else -> activity.startActivityForResult(
                Intent(
                    activity,
                    FileManagerActivity::class.java
                ), FileManagerActivity.CHOOSE_REQUEST
            )
        }
    }

    /** 从相册获取图片 **/
    private fun pickPicture(): Unit = PictureSelector.create(activity)
        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
        .loadImageEngine(GlideEngine.createGlideEngine())
        .maxSelectNum(1)// 最大图片选择数量 int
        .minSelectNum(1)// 最小选择数量 int
        .imageSpanCount(4)// 每行显示个数 int
        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
        .previewImage(true)// 是否可预览图片 true or false
        .isCamera(true)// 是否显示拍照按钮 true or false
        .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
        .compress(true)// 是否压缩 true or false
        .enableCrop(false)
        .isGif(true)// 是否显示gif图片 true or false
        .openClickSound(false)// 是否开启点击声音 true or false
        .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
        .minimumCompressSize(100)// 小于100kb的图片不压缩
        .synOrAsy(true)//同步true或异步false 压缩 默认同步
        .forResult(PictureConfig.CHOOSE_REQUEST)//结果回调onActivityResult code

    /**
     * 处理Activity返回结果
     * @param requestCode 请求码
     * @param resultCode 结果码
     * @param data 数据包
     */
    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            PictureConfig.CHOOSE_REQUEST -> { //图片选择
                when (resultCode) {
                    Activity.RESULT_OK -> {
                        // 图片、视频、音频选择结果回调
                        val selectList = PictureSelector.obtainMultipleResult(data)
                        val imgPath = with(selectList.firstOrNull()) {
                            when {
                                this == null -> null
                                else -> compressPath ?: path
                            }
                        }
                        if (!imgPath.isNullOrEmpty()) {
                            val imgFile = File(imgPath)
                            if (imgFile.exists()) {
                                val uris = arrayOf(activity.getUriFromFileProvider(imgFile))
                                fileUploadCallback?.onReceiveValue(uris)
                                fileUploadCallback = null
                                return
                            }
                        }
                    }
                }
                fileUploadCallback?.onReceiveValue(null)
                fileUploadCallback = null
            }
            FileManagerActivity.CHOOSE_REQUEST -> { //文件选择
                when (resultCode) {
                    Activity.RESULT_OK -> {
                        val filePath = data?.getStringExtra("file")
                        if (!filePath.isNullOrEmpty()) {
                            val file = File(filePath)
                            if (file.exists()) {
                                val uris = arrayOf(activity.getUriFromFileProvider(file))
                                fileUploadCallback?.onReceiveValue(uris)
                                fileUploadCallback = null
                                return
                            }
                        }
                    }
                }
                fileUploadCallback?.onReceiveValue(null)
                fileUploadCallback = null
            }
        }
    }

}